import {Component, OnInit, Injector, ViewChild,Optional,Inject,InjectionToken} from '@angular/core';

import { WaterSamplingServiceProxy ,
    SamplingPointDto ,
    ChangePointLocationDto ,
    RiversNameValueDto,
    GetAllSamplingPointsOutputDto,
    WaterDetectionCriterionServiceProxy,
    GetAllSamplingPointsInputDto,
    NameValue
} from '@shared/service-proxies/service-proxies';

import { Abp } from '@core/net/abp';


import {AppComponentBase} from '@shared/app-component-base';
import { SettingsService, Layout } from '@delon/theme';

import {FileDownloadService} from '@shared/utils/file-download.service.ts';

import * as moment from 'moment';
import * as _ from 'lodash';
import * as html2canvas from 'html2canvas';

import { SamplingInfo,
    Sampling,
    MarkData,
    DetectionValue,
    WaterWindowVm } from './../water-sampling.model';


import { WaterWindowComponent } from './water-window.component';

import { MapOptions , TMapInstance} from './../../../tianditu/types/Map';

import { Point } from './../../../tianditu/types/point';
import { MarkerOptions } from './../../../tianditu/types/Marker';
import { Control, ControlOptions, ControlPosition } from './../../../tianditu/types/Control';
import { InfoWindow, InfoWindowOptions } from './../../../tianditu/types/InfoWindow';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

import { AppConsts } from '@shared/AppConsts';

@Component({selector: 'app-reception-map', templateUrl: './reception-map.component.html', styleUrls: ['./reception-map.component.less']})
export class ReceptionMapComponent  extends AppComponentBase  implements OnInit {

    quickMenu = false;

    markerDraggabled = false;

    options: MapOptions;

    riverIds: string[] ;
    criterions: string[];
    limitTypes: number[];

    riverTotal= 0;
    dataTotal= 0;

    rivers: Array<RiversNameValueDto>;
    criterionSource: Array<NameValue>;

    loading = false;


     @ViewChild('openwin')
     openwin: WaterWindowComponent;


     dateRange: {
         start: moment.Moment;
         end: moment.Moment
     };

    public markers: Array < {
        point: Point;
        options?: MarkerOptions,
        data: SamplingPointDto
    } >;

    pieOpt={
        salesPieData : [
            
        ],
        total : 0,
        colors:['#FF0000','#00FF00']
    }

    dataSource:SamplingPointDto[];

    private baseUrl: string;

    constructor(
        injector: Injector,
        public settingService: SettingsService,
        private waterSamplingService: WaterSamplingServiceProxy,
        private wdcService: WaterDetectionCriterionServiceProxy,
        private _fileDownloadService:FileDownloadService,
        @Optional() @Inject(API_BASE_URL) baseUrl?: string
    ) {
        super(injector);
        this.riverIds = [];
        this.criterionSource =[ ];

        const date = new Date();

        this.dataSource = [];

        this.dateRange = {
            start : moment(date).subtract(1, 'years'),
            end : moment(date)
        };

        console.log(baseUrl);
        this.baseUrl = baseUrl ? baseUrl : "";

    }

    chartColors=[];

    ngOnInit() {

        this.options = {
            center: {
                lng: 122.096814,
                lat: 39.7066
            },
            zoom: 9
        };

        this.markers = [
        ];

        this.loadRivers();
        this.loadCriterions();
    }

    changeDraggable() {

        this.markerDraggabled = !this.markerDraggabled;

        _.forEach(this.markers, (item) => {
            item.options = {
                draggable: this.markerDraggabled
            };

        });

    }

    /*


    添加图例
 const div = map.getContainer();

        const copyrightDiv = div.querySelector('.tdt-control-copyright');

        const link = document.createElement('img');
        link.src = '/assets/img/icon/tuli.png';

        // TODO:编译不通过
        // link.style = ` display:inline;position:relative;bottom:4px;white-space:nowrap;padding:0 0 0 3px; `;
        link.width = 106;
        link.height = 22;
        copyrightDiv.children[0].appendChild(link);



    */

    saveImage(){

        // 使用html2canvas插件，将数据源中的数据转换成画布。
        html2canvas(document.querySelector("#map"),{
           // allowTaint:true,
            // useCORS:true
            "useCORS": true,
            "allowTaint": true, 
            "logging": true,
        }).then(canvas => {
            // 修改生成的宽度
            canvas.style.width = "1000px";
            console.log(canvas);

           // var img = canvas.toDataURL()
            // window.open(img);
            
            // let canvasImg = canvas.toDataURL("image/png");//.replace("image/png","image/octet-stream");

            // window.location.href = canvasImg;
            // this.downloadFile("导出图片", canvasImg);
        });

    }

    downloadFile(filename, content) {
        var base64Img = content;
        var oA = document.createElement('a');
        oA.href = base64Img;
        oA.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        oA.dispatchEvent(event);
    }


    mapLoaded($event) {

        var settingLegend=Abp.setting.get("App.TenantManagement.Legend");
        
//;App.TenantManagement.Legend

        var legend="/assets/img/icon/tuli.png";
        if(settingLegend){
            let url_ = AppConsts.remoteServiceBaseUrl + "/Common/Images/MapImages/"+settingLegend;
            // /Common/Images/MapImages/Legend0.jpg
            legend=url_+'?dt='+new Date().getTime();
        }

        const map = $event as TMapInstance;

        const zoomControl = new window.T.Control.Zoom();
        map.addControl(zoomControl);

        const div = map.getContainer();
        const copyrightDiv = div.querySelector('.tdt-control-copyright');

        const link = document.createElement('img');
        link.src = legend;

        // TODO:编译不通过
        link.attributes['style'] = ` display:inline;position:relative;bottom:4px;white-space:nowrap;padding:0 0 0 3px; `;
        link.width = 350;
        link.height = 50;

        const controlDiv = copyrightDiv.children[0] as HTMLElement;

        controlDiv.setAttribute('style', 'height:40px'); // = `height:40px`;

        controlDiv.appendChild(link);

        // 修复IE11 没有 remove方法
        const ch1 = controlDiv.children[0];
        const ch2 = controlDiv.children[1];
        controlDiv.removeChild(ch1);
        controlDiv.removeChild(ch2);
       
       this.load();

    }

    loadRivers() {
        this.waterSamplingService.getAllRiversNames()
            .subscribe((res) => {
                this.rivers = res;
            });
    }

    loadCriterions(){

        this.wdcService.getAllCriterions()
            .subscribe((res) => {
                this.criterionSource = res;
            });

    }



    load(){

        this.loading = true;
        this.waterSamplingService.getAllSamplingPoints(
            this.dateRange.start,
            this.dateRange.end,
            this.riverIds,
            this.criterions,
            this.limitTypes
        )
        .finally(() => {
            this.loading = false;
        })
        .subscribe((res: GetAllSamplingPointsOutputDto) => {

         
            this.dataSource=res.items;

            this.chartColors = res.colors;

            this.markers = _.map(res.items, (item) => {


                let imgUrl='/assets/img/icon/marker-' + item.waterLimitType + '.png';
                if(item.markerImage){

                    let url_ = AppConsts.remoteServiceBaseUrl + "/Common/Images/MapImages/"+item.markerImage;
                    
                    imgUrl = url_;
                }

                const icon = new window.T.Icon({
                    iconUrl:imgUrl ,
                });

                return {
                    point: {
                        lng: item.gps.lng,
                        lat: item.gps.lat
                    },
                    data: item,
                    options: {
                        icon : icon
                    }
                };
            });

            this.riverTotal = res.riversTotal;
            this.dataTotal = res.dataTotal;

            this.switch(1);

        });

    }

    getMarkerImage(markerImage){
        let url_ = AppConsts.remoteServiceBaseUrl + "/Common/Images/MapImages/"+markerImage;
        return url_;

    }

    markerDragended(data, $e) {

        const id = data.id;
        const lnglat = $e.marker.getLngLat();

        this.changeLngLat(id, lnglat.getLng(), lnglat.getLat());

    }

    changeLngLat(id: string, lng: number, lat: number) {
        const input = new ChangePointLocationDto();
        input.pointId = id;
        input.lng = lng;
        input.lat = lat;
        this.waterSamplingService.changePointLocation(input)
            .subscribe((res) => {
                this.notify.success('修改点位成功');
            });
    }

    public showWindow({e, marker, map}: any, data: SamplingPointDto): void {

        /**/
        const html = this.openwin.nativeElement;

        let vm = new WaterWindowVm();
        vm.data = data;
        vm.selected = data.samplings[0];

        this.openwin.vm = vm;
        map.openInfoWindow(new window.T.InfoWindow(html, {
            minWidth: 500
        }), marker.getLngLat());
        const zoom = map.getZoom();
        const center = marker.getLngLat();

        map.centerAndZoom(center, zoom);

        setTimeout(() => {
            map.panBy({
                x: 0,
                y: -150
            });

        }, 300);



    }

    export(){

        var dto = new GetAllSamplingPointsInputDto();
        dto.start = this.dateRange.start;
        dto.end = this.dateRange.end;
        dto.norms = this.criterions;
        dto.pointIds = this.riverIds;

        this.waterSamplingService.exportExcel(dto)
            .subscribe(file=>{
                this._fileDownloadService.downloadTempFile(file);
            });

    }

    switch(e){
        if(e===1){

            let source=_.sortBy(this.dataSource, [function(o) { return o.nameValue; }]);

            let group = _.groupBy(source,(item)=>{
                return item.nameColor;
            });

            let keys = _.keys(group);
 
            let nameValue = _.map(keys,(key)=>{
              //  let value = key*1.0;

                let colorValue = _.find(this.chartColors,i=>{
                    return i.name == key;
                });
                
                let name ="";
                let color="#0000ff";

                if(colorValue==undefined){

                    /*
                    if ( value === 1 ) {
                        name = 'I';
                        color='#0000ff';
                    }
            
                    if ( value === 2 ) {
                        name = 'II';
                        color='#0000ff';
                    }
            
                    if ( value === 3 ) {
                        name = 'III';
                        color='#00ff00';
                    }
            
                    if ( value === 4 ) {
                        name = 'IV';
                        color='#ffff00';
                    }
            
                    if ( value === 5 ) {
                        name = 'V';
                        color='#ff7f00';
                    }
            
                    if ( value === 6 ) {
                        name = '劣V';
                        color='#ff0000';
                    }
                    */

                }else{
                  
                    name= colorValue.name;
                    color=colorValue.color
                }

               
                
   
                return {
                    x:name,
                    y:group[key].length,
                    color:color
                }
            });

            const colors = _.map(nameValue,(item)=>{
                return item.color;
            });

           

            this.pieOpt.salesPieData = nameValue;
            this.pieOpt.total = nameValue.reduce((pre, now) => now.y + pre,0);
            this.pieOpt.colors=colors;


        }
    }

}
